<?php
// 流式输出诊断脚本
header('Content-Type: text/plain; charset=utf-8');

echo "=== 流式输出诊断工具 ===\n\n";

// 1. 检查PHP配置
echo "1. PHP配置检查:\n";
echo "   PHP版本: " . PHP_VERSION . "\n";
echo "   SAPI: " . PHP_SAPI . "\n";
echo "   output_buffering: " . ini_get('output_buffering') . "\n";
echo "   zlib.output_compression: " . ini_get('zlib.output_compression') . "\n";
echo "   implicit_flush: " . ini_get('implicit_flush') . "\n";
echo "   max_execution_time: " . ini_get('max_execution_time') . "\n";
echo "   memory_limit: " . ini_get('memory_limit') . "\n\n";

// 2. 检查SSE相关头信息
echo "2. SSE相关头信息检查:\n";
$headers = [
    'Content-Type: text/event-stream',
    'Cache-Control: no-cache',
    'Connection: keep-alive',
    'Access-Control-Allow-Origin: *'
];

foreach ($headers as $header) {
    echo "   设置头: $header\n";
}
echo "\n";

// 3. 检查服务器环境
echo "3. 服务器环境检查:\n";
echo "   Server Software: " . ($_SERVER['SERVER_SOFTWARE'] ?? 'Unknown') . "\n";
echo "   Server Address: " . ($_SERVER['SERVER_ADDR'] ?? 'Unknown') . "\n";
echo "   Remote Address: " . ($_SERVER['REMOTE_ADDR'] ?? 'Unknown') . "\n";
echo "   Request Method: " . ($_SERVER['REQUEST_METHOD'] ?? 'Unknown') . "\n\n";

// 4. 检查输出缓冲区
echo "4. 输出缓冲区检查:\n";
echo "   当前缓冲区层级: " . ob_get_level() . "\n";
echo "   缓冲区状态: " . (ob_get_level() > 0 ? '启用' : '禁用') . "\n\n";

// 5. 执行流式输出测试
echo "5. 流式输出测试:\n";
echo "   开始发送测试数据...\n";

// 清除所有输出缓冲区
while (ob_get_level()) {
    ob_end_clean();
}

// 设置流式输出头
header('Content-Type: text/event-stream; charset=utf-8');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('Access-Control-Allow-Origin: *');

// 禁用PHP输出缓冲
ini_set('output_buffering', 'off');
ini_set('zlib.output_compression', 'off');
ini_set('implicit_flush', '1');

// 立即刷新输出
if (function_exists('apache_setenv')) {
    apache_setenv('no-gzip', '1');
}

// 发送初始数据
echo "data: 测试开始\n\n";
flush();

// 发送几条测试消息
for ($i = 1; $i <= 10; $i++) {
    echo "data: 测试消息 $i\n\n";
    flush();
    
    // 模拟延迟
    usleep(500000); // 0.5秒
}

echo "data: 测试结束\n\n";
flush();

echo "   测试数据发送完成\n\n";

// 6. 建议解决方案
echo "6. 建议解决方案:\n";
echo "   - 检查服务器上的Nginx/Apache配置，确保没有缓冲设置\n";
echo "   - 检查是否有反向代理或CDN影响流式传输\n";
echo "   - 确认防火墙或安全组没有限制长连接\n";
echo "   - 检查PHP-FPM配置中的缓冲设置\n";
echo "   - 确认服务器上的timeout设置足够长\n\n";

echo "=== 诊断完成 ===\n";
?>